import glob
import os
import subprocess
import argparse
from astropy.io import fits
from astropy.coordinates import SkyCoord
from loguru import logger

import subprocess
import platform
import ntpath
from screeninfo import get_monitors
from tools import utils


def get_screen_resolution():
	monitor = get_monitors()[0]  # 获取主显示器信息
	width = int(monitor.width * 0.7)
	height = int(monitor.height * 0.7)
	return width, height

def generate_region_file(fits_file, ra_val,dec_val, savepath=None):

    filename=ntpath.basename(fits_file)
    base_name=fits_file[:-5].split("_")[-2]
    
    catalog = fits.getdata(fits_file.replace(".fits", "_sexcat_CalMag.fits"), ext=2)
    
    
    matched_star=utils.TargetXCatalogue(ra_val, dec_val,catalog)
    if matched_star:
        if "mr" in filename:
            calmag=matched_star["CALMAG_28"]
        else:
            calmag=matched_star["CALMAG_22"]
    else:
        calmag=0
            
    region_lines = []
    
    # Region file format: DS9 version 4.1
    region_lines.append('global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1')
    
    # 设置全局属性：颜色、字体等
    region_lines.append('fk5')

    
    # 生成 region 语法行，fk5 表示赤道坐标系
    line = f'circle({ra_val},{dec_val},12.626") # width=4 font="times 16 bold roman" text='+'{'+str(round(calmag,2))+" | "+base_name+"}"
    region_lines.append(line)

    # 拼接所有 region 内容
    region_content = "\n".join(region_lines)

    output_file=os.path.join(savepath,filename+".reg")
    # 写入到指定的 region 文件
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(region_content)

    # 返回生成的 region 文件路径
    return output_file


def open_ds9_with_regions(fits_files,target_ra,target_dec,temp_dir=None, region_file1=None, region_file2=None):
    """
    使用 DS9 打开多个 FITS 文件，加载一个或两个 region 文件，并自动全屏显示和调整图像大小以适应窗口，同时锁定帧和 WCS.

    :param fits_files: 多个 FITS 文件路径的列表.
    :param region_file1: 第一个 Region 文件路径.
    :param region_file2: 第二个 Region 文件路径 (可选).
    """
    try:
        # 获取当前屏幕的分辨率
        screen_width, screen_height = get_screen_resolution()
        # 判断操作系统类型
        system_type = platform.system()

        # 根据操作系统类型选择 DS9 可执行文件路径
        if system_type == "Windows":
            ds9_command = "C:/SAOImageDS9/ds9.exe"
        elif system_type == "Linux":
            ds9_command = "ds9"  # 假设 ds9 已添加到系统路径中
        elif system_type == "Darwin":  # macOS 的系统类型
            ds9_command = "/Applications/SAOImage DS9.app/Contents/MacOS/ds9"
        else:
            logger.info(f"未支持的操作系统: {system_type}")
            return

        # 构建 DS9 命令
        command = [ds9_command]

        # 添加锁帧和 WCS 的命令
        command.extend(["-lock", "frame", "wcs"])

        for fits_file in fits_files:
            
            output_file=generate_region_file(fits_file,target_ra,target_dec,temp_dir)
            command.extend([fits_file, "-region", output_file])
            
            
            if region_file1:
                command.extend(["-region", region_file1])
            if region_file2:
                command.extend(["-region", region_file2])
                
            command.extend(["-zoom", "to", "fit", "-scale", "mode", "zscale"])

            
        command.extend(["-geometry", f"{screen_width}x{screen_height}"])
        

        # 打开 DS9，并加载 FITS 文件和区域文件，同时进行全屏显示和缩放适应窗口\
        logger.info(" ".join(command))
        subprocess.run(command)
        logger.info(f"DS9 打开多个 FITS 文件并加载区域文件 {region_file1} 和 {region_file2} 成功！")

    except FileNotFoundError:
        import traceback
        logger.error(traceback.format_exc())
        logger.info("请确保 DS9 已安装，并且路径正确或在系统路径中可用。")



def open_ds9_without_regions(fits_files,target_ra,target_dec,temp_dir=None, region_file1=None, region_file2=None):
    """
    使用 DS9 打开多个 FITS 文件，加载一个或两个 region 文件，并自动全屏显示和调整图像大小以适应窗口，同时锁定帧和 WCS.

    :param fits_files: 多个 FITS 文件路径的列表.
    :param region_file1: 第一个 Region 文件路径.
    :param region_file2: 第二个 Region 文件路径 (可选).
    """
    try:
        # 获取当前屏幕的分辨率
        screen_width, screen_height = get_screen_resolution()
        # 判断操作系统类型
        system_type = platform.system()

        # 根据操作系统类型选择 DS9 可执行文件路径
        if system_type == "Windows":
            ds9_command = "C:/SAOImageDS9/ds9.exe"
        elif system_type == "Linux":
            ds9_command = "ds9"  # 假设 ds9 已添加到系统路径中
        elif system_type == "Darwin":  # macOS 的系统类型
            ds9_command = "/Applications/SAOImage DS9.app/Contents/MacOS/ds9"
        else:
            logger.info(f"未支持的操作系统: {system_type}")
            return

        # 构建 DS9 命令
        command = [ds9_command]

        # 添加锁帧和 WCS 的命令
        command.extend(["-lock", "frame", "wcs"])

        for fits_file in fits_files:
            
            
            command.extend([fits_file])
                  
            command.extend(["-zoom", "to", "fit", "-scale", "mode", "zscale"])

            
        command.extend(["-geometry", f"{screen_width}x{screen_height}"])
        

        # 打开 DS9，并加载 FITS 文件和区域文件，同时进行全屏显示和缩放适应窗口\
        logger.info(" ".join(command))
        subprocess.run(command)
        logger.info(f"DS9 打开多个 FITS 文件并加载区域文件 {region_file1} 和 {region_file2} 成功！")

    except FileNotFoundError:
        logger.info("请确保 DS9 已安装，并且路径正确或在系统路径中可用。")

def main():

    targetName = "p59474" 
    # 目标名称，用于后续路径和文件命名
    filterName="v"
    target_ra = 215.578104     # 示例：RA
    target_dec = +50.501192   # 示例：Dec
    # 用于存储在不同滤光片下计算到的极限星等，便于在处理结束后统一查看或统计

    # 定义两个需要写入的结果文件：
    #   1) target_name：主要保存最终的测光结果，如极限星等、曝光时间等
    #   2) target_name_zp：主要保存光度归一化时参考图像、相对光度比等零点信息
    maindir = "."
    imgdir = os.path.join(maindir, "images", targetName)
    temp_reg = os.path.join(maindir, "images", targetName,"temp_reg")
    utils.ensure_directories(temp_reg)
    
    imgListName = os.path.join(imgdir, f"images_{filterName}.list")
    
    imgList = open(imgListName, "r").read().splitlines()
    maindir = "."
    confdir = os.path.join(maindir, "config")
    
    imgListArr=[]
    imgListArr_sub=[]
    sub=480
    for im_ in imgList:
        temp_=os.path.join(imgdir,im_)
        filterName=fits.getheader(temp_)["filter"]
        imgListArr.append(temp_)
        if filterName in ['u', 'v', 'g', 'r']:
            ipixScale = 0.429
            x=sub/ipixScale
            y=sub/ipixScale
        elif filterName in ['i', 'z']:
            ipixScale = 0.286
            x=sub/ipixScale
            y=sub/ipixScale
        
        swarpConf = os.path.join(confdir, "default.swarp")
        swarpComd1 = "swarp %s -c %s -IMAGEOUT_NAME %s -WEIGHTOUT_NAME %s "
        swarpComd2 = f"-RESAMPLE_DIR %s -PIXEL_SCALE {ipixScale} -SUBTRACT_BACK N -VERBOSE_TYPE FULL "
        swarpComd3 = f"-CENTER_TYPE MANUAL -CENTER {target_ra},{target_dec} -IMAGE_SIZE {x},{y} "
        swarpComd = swarpComd1 + swarpComd2 + swarpComd3

        products_dir = os.path.join(maindir, "products", targetName,"sub")
        utils.ensure_directories(products_dir)
        
        mosaicName = os.path.join(products_dir, f"zMosaic_{targetName}_{filterName}.fits")
        mosaicWghName = mosaicName[:-4] + "wgh.fits"
        swp = swarpComd % (temp_, swarpConf, mosaicName, mosaicWghName, products_dir)
        logger.info(swp)
        os.system(swp)
        logger.info(mosaicName)
        imgListArr_sub.append(mosaicName)
   
    open_ds9_with_regions(imgListArr,target_ra,target_dec, temp_reg)
    open_ds9_without_regions(imgListArr_sub,target_ra,target_dec, temp_reg)


                
    

if __name__ == "__main__":
    main()
